<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\goods\Order;
use app\common\controller\Api;
use app\common\controller\Payment;
use app\common\model\FishingGroundOrdersGroups;
use app\common\model\UserMoneyLog;
use app\common\model\UserScoreLog;
use think\Controller;
use think\Db;
use think\Request;


class Fishinggroundpositions extends Api
{
    private static $model;
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new \app\common\model\FishingGroundPositions();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function lists()
    {
//        $page = input('page', 1);
//        $pageSize = input('page_size', 10);
//        $start = ($page - 1) * $pageSize;
//
//        $groundId = input('ground_id');
//        if (!$groundId) {
//            $this->error('参数缺失！');
//        }
//
//        $userId = $this->auth->id;
//        $where = [
//            'status' => 1,
//            'user_id' => $userId,
//            'ground_id' => $groundId
//        ];
//
//        $list = self::$model->where($where)->order('createtime desc')->limit($start, $pageSize)->select();
//        if ($list) {
//            $feedback_types = config('site.feedback_types');
//            foreach ($list as $val) {
//                $val->avatar = \app\common\model\User::where('id', $val->user_id)->value('avatar');
//                $val->type_name = $feedback_types[$val->type];
//            }
//        }
//        $total = self::$model->where($where)->count();
//        $this->success('反馈记录', ['list' => $list, 'total' => $total]);
    }

    /**
     * 钓场反馈
     */
    public function create()
    {
//        $groundId = input('ground_id');
//        if (!$groundId) {
//            $this->error('参数缺失！');
//        }
//
//        $groundInfo = \app\common\model\FishingGround::find($groundId);
//        if (!$groundInfo) {
//            $this->error('该钓场不存在！');
//        }
//
//        if ($groundInfo->source_type != 2) {
//            $this->error('该钓场非野钓场！');
//        }
//
//        $content = input('content');
//        if (!$content) {
//            $this->error('请输入反馈内容！');
//        }
//
//        $type = input('type');
//        $mobile = input('mobile');
//
//        $userId = $this->auth->id;
//        $fdata = [
//            'user_id' => $userId,
//            'content' => $content,
//            'ground_id' => $groundId,
//            'type' => $type,
//            'mobile' => $mobile,
//        ];
//
//        $ret = self::$model->create($fdata);
//        if (!$ret) {
//            $this->error('反馈失败！');
//        }
//
//        $this->success('反馈成功！');
    }

    /**
     * 钓位详情
     */
    public function read()
    {
        $id = input('id');
        $row_info = self::$model->find($id);
        if (!$row_info) {
            $this->error('该钓位不存在！');
        }

        if ($row_info->status != 0) {
            $this->error('该钓位不可预约！');
        }

        $fishsInfo = \app\common\model\FishingGroundFishs::where('id', $row_info->fishs_id)->find();
        $priceInfo = \app\common\model\FishingGroundPrices::where('ground_id', $fishsInfo->ground_id)->where('type', $fishsInfo->type)->find();
        $row_info->prices = $priceInfo;

        $fish_types = config('site.fish_types');
        $row_info->fish_name = $fish_types[$fishsInfo->type];

        $fishing_ground_types = config('site.fishing_ground_types');
        $typeInfo = \app\common\model\FishingGroundTypes::where('id', $fishsInfo->types_id)->find();
        $row_info->type_name = $fishing_ground_types[$typeInfo->type];

        $groundInfo = \app\common\model\FishingGround::where('id', $fishsInfo->ground_id)->find();
        $row_info->address = $groundInfo->address;

        $this->success('钓位详情', $row_info);
    }

    /**
     * 预约订单
     */
    public function createOrder()
    {
        $id = input('id');
        $row_info = self::$model->find($id);

        if (!$row_info) {
            $this->error('该钓位不存在！');
        }

        if ($row_info->status != 0) {
            $this->error('该钓位不可预约！');
        }

        $orderType = input('order_type');
        if (!in_array($orderType, [1, 2])) {
            $this->error('请选择预约类型！');
        }

        $isScore = input('is_score');
        $userId = $this->auth->id;
        $user = \app\common\model\User::find($userId);

        $fishsInfo = \app\common\model\FishingGroundFishs::where('id', $row_info->fishs_id)->find();
        $priceInfo = \app\common\model\FishingGroundPrices::where('ground_id', $fishsInfo->ground_id)->where('type', $fishsInfo->type)->find();

        $groupType = input('group_type', 0);
        if ($orderType == 1) {
            // 单独购买，由用户级别决定价格
            if ($user->level == 1) {
                $price = $priceInfo->original_price;
            } else {
                $price = $priceInfo->member_price;
            }
        } else {
            // 拼团购买
            if (!$groupType) {
                $this->error('必须选择拼团类型！');
            }
            $group_prices = $priceInfo->group_price;
//            $price = $group_prices[$groupType];
            $price = 10;
        }

        if ($isScore == 1) {
            $needScore = min($user->score, $price);
            $needMoney = round($price - $needScore);
        } else {
            $needScore = 0;
            $needMoney = $price;
        }

        $payType = input('paytype', 0);
        $platformType = input('platform_type', 1);//1小程序，2微信公众号，3h5，4app
        $timeId = input('time_id', 1);
        $startTime = input('start_time');
        if (!$startTime) {
            $this->error('必须选择开始时间！');
        }

        $orderNum = create_order($userId);
        $apply_hours_arr = config('site.apply_hours');
        $endTime = $startTime + $apply_hours_arr[$timeId] * 3600;

        $serviceId = 0;
        $groundInfo = \app\common\model\FishingGround::find($fishsInfo->ground_id);
        if ($groundInfo->source_type == 2 && $groundInfo->source_id > 0) {
            $serviceId = \app\common\model\WanlshopShop::where('id', $groundInfo->source_id)->value('service_id');
        }

        // 订单记录
        $odata = [
            'order_num' => $orderNum,
            'user_id' => $userId,
            'position_ids' => $id,
            'order_type' => $orderType,
            'pay_type' => $payType,
            'platform_type' => $platformType,
            'group_type' => $groupType,
            'group_nums' => 0,
            'paytime' => time(),
            'status' => 0,
            'price' => $price,
            'score' => $needScore,
            'money' => $needMoney,
            'start_time' => $startTime,
            'time_id' => $timeId,
            'service_id' => $serviceId,
            'end_time' => $endTime,
        ];

        if ($orderType == 2) {
            $group_cates_nums_arr = config('site.group_cates_nums');
            $total_nums = $group_cates_nums_arr[(int)$groupType];
        } else {
            $total_nums = 0;
        }
        $odata['group_total_nums'] = $total_nums;
        if ($needMoney == 0) {
            // 全用积分支付
            // 启动事务
            Db::startTrans();
            try {
                //积分扣减
                $orderNum = $this->handleOrder($user, $row_info, $needScore, $needMoney, $price, $groupType, $odata, $orderType);
                $msg = '预约成功！';
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            if ($needScore == 0) {
                // 全用现金支付
                if ($payType == 3) {
                    if ($user->money < $needMoney) {
                        $this->error('可用余额不足！');
                    }

                    // 启动事务
                    Db::startTrans();
                    try {
                        // 余额扣减
                        $orderNum = $this->handleOrder($user, $row_info, $needScore, $needMoney, $price, $groupType, $odata, $orderType);
                        $msg = '预约成功！';
                        // 提交事务
                        Db::commit();
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        $this->error($e->getMessage());
                    }

                } else {
                    // 订单记录
                    $oInfo = \app\common\model\FishingGroundOrders::create($odata);

                    // 拼团记录
                    $orderNum = create_order($row_info->id);
                    $gdata = [
                        'user_id' => $user->id,
                        'order_num' => $orderNum,
                        'position_id' => $row_info->id,
                        'order_id' => $oInfo->id,
                        'group_type' => $groupType,
                        'price' => $price,
                    ];

                    FishingGroundOrdersGroups::create($gdata);
                }
            } else {
                //部分现金部分积分
                if ($payType == 3) {
                    if ($user->money < $needMoney) {
                        $this->error('可用余额不足！');
                    }

                    // 积分+余额扣减
                    $orderNum = $this->handleOrder($user, $row_info, $needScore, $needMoney, $price, $groupType, $odata, $orderType);

                } else {
                    // 订单记录
                    $oInfo = \app\common\model\FishingGroundOrders::create($odata);

                    // 拼团记录
                    $orderNum = create_order($row_info->id);
                    $gdata = [
                        'user_id' => $user->id,
                        'order_num' => $orderNum,
                        'position_id' => $row_info->id,
                        'order_id' => $oInfo->id,
                        'group_type' => $groupType,
                        'price' => $price,
                    ];

                    FishingGroundOrdersGroups::create($gdata);
                    $msg = '订单生成成功！';
                }
            }
        }

        $this->success($msg, ['order_num' => $orderNum, 'position_id' => $id]);

    }

    /**
     * 处理订单
     * @param $user
     * @param $row_info
     * @param $score 积分额度
     * @param $money 余额额度
     * @param $price
     * @param $groupType
     * @param int $orderType 1为独资2为拼团
     */
    private function handleOrder($user, $row_info, $score, $money, $price, $groupType, $odata, $orderType = 1)
    {
        if ($score > 0) {
            $user->score -= $score;
        }

        if ($money > 0) {
            $user->money -= $money;
        }

        $user->save();

        // 生成订单
        $odata['status'] = 1;
        $oInfo = \app\common\model\FishingGroundOrders::create($odata);

        // 积分流水
        if ($score > 0) {
            $before = $user->score + $score;
            $sdata = [
                'user_id' => $user->id,
                'record_type' => 0,
                'score' => $score,
                'before' => $before,
                'after' => $user->score,
                'memo' => '预约' . $row_info->name . '扣减积分',
            ];

            UserScoreLog::create($sdata);
        }

        if ($money > 0) {
            // 余额流水
            $before = $user->money + $money;
            $orderNum = create_order($user->id);
            $mdata = [
                'order_num' => $orderNum,
                'user_id' => $user->id,
                'record_type' => 0,
                'money' => $money,
                'before' => $before,
                'after' => $user->money,
                'relation_type' => 1,// 钓场预约
                'relation_id' => $oInfo->id,
                'memo' => '预约' . $row_info->name . '扣减余额',
            ];

            UserMoneyLog::create($mdata);
        }

        // 更新钓位为已预约
        self::$model->where('id', $row_info->id)->update(['status' => 1]);

        // 拼团记录
        if ($orderType == 2) {
            $orderNum = create_order($row_info->id);
            $gdata = [
                'user_id' => $user->id,
                'order_num' => $orderNum,
                'position_id' => $row_info->id,
                'order_id' => $oInfo->id,
                'group_type' => $groupType,
                'price' => $price,
                'status' => 1,
            ];

            FishingGroundOrdersGroups::create($gdata);
            // 更新订单已预约人数
            \app\common\model\FishingGroundOrders::where('id', $oInfo->id)->update(['group_nums' => 1]);
        }
    }
}
